package com.cmpan.networkdisk.controller;

import com.cmpan.networkdisk.model.Comment;
import com.cmpan.networkdisk.model.User;
import com.cmpan.networkdisk.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * ClassName:CommentController
 * Package:com.cmpan.networkdisk.controller
 * Description:
 *
 * @Date:2020/7/20 16:18
 * @com.chuangmei
 */
@Controller
public class CommentController {

    //service
    @Autowired
    private CommentService commentService;

    @GetMapping("/commentmessage")
    public String goComment(HttpServletRequest request, Model model){
        //取到User
        User user = (User) request.getSession().getAttribute("user");

        if (user != null)
            model.addAttribute("user",user);

        //查询所有的评论信息
        List<Comment> comments = commentService.queryAll();

        if (comments != null)
            model.addAttribute("comments",comments);

        return "comment";
    }

    @PostMapping("/publishcomment")
    public String publish(Comment comment,HttpServletRequest request, Model model){

        //user
        User user = (User) request.getSession().getAttribute("user");

        //设置头像,创建时间,管理员
        if (comment != null){
            comment.setCreatedate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            if (user != null)
                if (user.getNickname().equals(comment.getNickname()))
                    comment.setAdmin(1);
        }
        //写入
        int count = commentService.addComment(comment);

        return count > 0 ? "redirect:/commentmessage" : "error/error";
    }

}
